<template>
<div>
<!--  查询和清空按钮-->
  <el-row>
    <el-col :span="5"><el-input placeholder="用户名" v-model="username"></el-input></el-col>
    <el-col :span="2"><el-button
      icon="el-icon-search"
      type="primary"
      style="margin-left: 10px"
      @click="searchUser"
    >查询</el-button></el-col>
    <el-col :span="2"><el-button style="margin-left: 5px" @click="username = null;getUserList()">清空</el-button></el-col>
  </el-row>
<!--  添加和批量删除-->
  <el-row style="margin: 20px 0">
    <el-col :span="1"><el-button type="primary" @click="addOrEditUserDialogVisible = true">添加</el-button></el-col>
    <el-col :span="2" style="padding-left: 25px"><el-button type="danger" :disabled="deleteIdList.length===0" @click="selectDelete">批量删除</el-button></el-col>
  </el-row>
<!--  用户列表展示表格-->
  <el-table
    v-loading="userLoadingVisible"
    border
    ref="multipleTable"
    :data="userList"
    tooltip-effect="dark"
    style="width: 100%"
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
    <el-table-column label="用户名" width="170" prop="username"></el-table-column>
    <el-table-column prop="nickName" label="用户昵称" width="170"></el-table-column>
    <el-table-column prop="roleName" label="权限列表" width="180"></el-table-column>
    <el-table-column prop="gmtCreate" label="创建时间" width="180"></el-table-column>
    <el-table-column prop="gmtModified" label="更新时间" width="180">
    </el-table-column><el-table-column prop="address" label="操作">
       <template slot-scope="scope">
<!--      分配角色-->
         <el-button icon="el-icon-user" type="info" size="mini" @click="openAssignRole(scope.row)"></el-button>
<!--      修改用户信息-->
         <el-button icon="el-icon-edit" type="primary" size="mini" @click="openEdit(scope.row)"></el-button>
<!--      删除用户-->
         <el-popconfirm title="确定要删除此用户吗" @onConfirm="deleteUser(scope.row)">
         <el-button icon="el-icon-delete" slot="reference" type="danger" size="mini" style="margin-left: 10px"></el-button>
      </el-popconfirm>
    </template>
  </el-table-column>
  </el-table>
<!--  分页器-->
  <el-pagination
    style="margin-top: 15px;text-align: center"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[5, 10, 15, 20]"
    :page-size="pageSize"
    layout=" prev, pager, next, jumper,->,total, sizes"
    :total="total">
  </el-pagination>

<!--  添加和修改用户的dialog框-->
  <el-dialog
    title="星之卡比"
    :visible.sync="addOrEditUserDialogVisible"
    width="50%"
    :before-close="beforeArrOrEditDialog"
    >
    <el-form :model="saveUserInfo" label-width="80px" :rules="addOrEditRules" ref="addOrEditRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="saveUserInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="saveUserInfo.nickName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="saveUserInfo.password"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="beforeArrOrEditDialog">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>

<!--  给用户分配角色的dialog-->
  <el-dialog
    title="提示"
    :visible.sync="assignRoleDia"
    width="60%"
    :before-close="closeAssignRole">
    <el-checkbox-group v-model="roleCheckList">
      <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
    </el-checkbox-group>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeAssignRole">取 消</el-button>
      <el-button type="primary" @click="assignRole">确 定</el-button>
    </span>

  </el-dialog>

</div>
</template>

<script>
import cloneDeep from 'lodash/fp/cloneDeep'

export default {
  name: "User",
  data() {
    return {
      // 搜索用户的关键字
      username:null,

      userLoadingVisible: false, // 控制loading加载
      addOrEditUserDialogVisible: false, // 控制添加或修改用户的dialog框显示与隐藏
      assignRoleDia: false, // 控制给用户分配权限的dialog框的显示或隐藏

      currentPage: 1,
      total:0,
      pageSize:5,

      templateUserId:'', // 为了给用户添加角色顺便存的

      saveUserInfo:{},// 添加用户的表单信息
      userList:[], // 用户列表
      deleteIdList:[], // 批量删除的ID的列表
      roleCheckList:[], // 用户选择角色的复选框
      roleList:[], // 所有角色列表

      // 添加或或者编辑的表单验证规则
      addOrEditRules:{
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        nickName: [{required: true, message: '请输入昵称', trigger: 'blur'}],
        password: [{required: true, message: '密码长度为3到8位',trigger: 'blur'}]
      },

    }
  },
  methods:{
    // 发送请求获取基本的用户列表
    async getUserList(){
      this.userLoadingVisible = true
      let res = await this.$API.users.apiGetUserList({page: this.currentPage,limit: this.pageSize,searchObj: this.username})
      if(res.code===20000) {
        this.userList = res.data.items
        this.total = res.data.total
        this.userLoadingVisible = false
      }else {
        this.$message.error('发生错误啦')
        this.userLoadingVisible = false
      }
    },
    // 通过用户名搜索用户
    searchUser() {
      if(this.username === '') {
        this.$message.warning('关键词不可以为空')
        return
      }
      this.getUserList()
    },

    // 当前页面展示数量发生变化
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.getUserList()
    },
    // 当前页面数发生变化
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getUserList()
    },

    // 用户选项发生改变的回调
    handleSelectionChange(currentIdList){
      this.deleteIdList = currentIdList.map(item=>{
        return item.id
      })
    },

    // 添加或者编辑用户
    addUser() {
      this.$refs["addOrEditRef"].validate( flag=>{
        if(!flag) {
          this.$message.error('表单信息填写错误')
        }else {
          this.$API.users.apiSaveAndEditUser(this.saveUserInfo).then(result=>{
           if (result !== undefined) {
             this.$message.success(`${this.saveUserInfo.id ? '修改':'添加'}成功`)
             // 重新获取数据
             this.getUserList()
           }else {
             this.$message.warning('对吧起您的权限不够')
           }
           // 重置添加用户表单信息
           this.saveUserInfo = {}
           this.addOrEditUserDialogVisible = false
          })
        }
      })
    },
    // 删除用户
    async deleteUser(row) {
      let res = await this.$API.users.apiDeleteUser(row.id)
      if(res !== undefined) {
        this.$message.success('删除成功')
        this.currentPage  = 1
        this.getUserList()
      }else {
        this.$message.warning('您的权限不够')
      }
    },
    // 批量删除用户
    selectDelete(){
      this.$confirm(`确认删除选中的${this.deleteIdList.length}项`, '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(async () => {
        let res = await this.$API.users.apiSelectDelete(this.deleteIdList)
        if(res !== undefined) {
          this.$message.success('删除成功')
          this.getUserList()
        }else {
          this.$message.warning('对不起您的权限不够')
        }
        this.deleteIdList = []
      }).catch(()=>{
        this.$message.info('已取消删除')
      })
    },
    // 给用户分配角色
    async assignRole(){
      let res = await this.$API.users.apiAssignRole(this.templateUserId,this.roleCheckList.join(','))
      if(res.code===20000) {
        this.$message.success('修改用户角色成功')
        this.getUserList()
      }else{
        this.$message.warning('授予角色信息失败')
      }
      this.closeAssignRole()
    },

    // 打开编辑用户的dialog
    async openEdit(row) {
      this.addOrEditUserDialogVisible = true
      this.saveUserInfo = cloneDeep(row)
    },
    // 打开分配角色的dialog框
    async openAssignRole(row){
      this.templateUserId = row.id
      let res = await this.$API.users.apiGetUserRoleById(row.id)
      if(res.code === 20000) {
        this.roleCheckList = res.data.assignRoles.map(item=>item.id)
        this.roleList = res.data.allRolesList
      }
      this.assignRoleDia = true
    },
    // 添加或者编辑dialog关闭前的回调
    beforeArrOrEditDialog() {
      this.saveUserInfo = {}
      this.addOrEditUserDialogVisible = false
    },
    // 给用户分配角色的dialog框关闭前的回调
    closeAssignRole(){
      this.assignRoleDia = false
      this.roleCheckList = []
      this.roleList = []
      this.templateUserId = ''
    }
  },
  mounted() {
    // 获取用户基本列表
    this.getUserList()
  }
}
</script>

<style scoped>

</style>
